package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author kabuda
 * @create 2022-09-05 16:26
 * 文件上传和下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String filePath;

    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //本次file是临时文件，需要转存到指定位置，否则本次请求结束后临时文件将会删除
        log.info(file.toString());

        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdir();
        }

        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        filename =  UUID.randomUUID().toString() + suffix;

        try {
            file.transferTo(new File(filePath+filename));

        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filename);
    }

    @RequestMapping("/download")
    public void download(String name, HttpServletResponse response) {
        FileInputStream fis=null;
        ServletOutputStream os=null;
        try {
             fis = new FileInputStream(filePath+name);
             os = response.getOutputStream();

             response.setContentType("image/jpeg");
            int len;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
                os.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(os!=null)
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if(fis!=null)
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
